<template>
  <div class="chooseSignatory" style="margin-top: 40px;">
    <!-- 指派签署人弹框 -->
    <div>
      <slot name="remarks" />
      <MyTable
        id="id"
        ref="myTableRef"
        class="myTableClass"
        :is-mar-class="true"
        :table-data="signatoryData"
        :columns="signatoryLabel"
        :table-operation="signatoryOperation"
        @propClick="btnClick"
        @rowClick="rowClick"
      >
        <template #signSealAdminList="{ scope }">
          <!-- 印章管理员 -->
          <Tooltip
            :disabled="!scope.signSealAdminList"
            effect="dark"
            :content="scope.signSealAdminList"
            placement="top"
          >
            <div class="pms-zr-tableColor" @click="rowSales(scope)">{{ scope.signSealAdminList |
              signatorySeal }}</div>
          </Tooltip>
        </template>
        <template #signSignersList="{ scope }">
          <!-- 签署人 -->
          <Tooltip
            :disabled="!scope.signSignersList"
            effect="dark"
            :content="scope.signSignersList"
            placement="top"
          >
            <div class="pms-zr-tableColor" @click="rowFileName(scope)">{{ scope.signSignersList |
              signatorySeal }}</div>
          </Tooltip>
        </template>
      </MyTable>
      <pagination
        v-if="pageParam.total > 10"
        :is-popper-body="false"
        :total="pageParam.total"
        :page.sync="pageParam.pageNum"
        :limit.sync="pageParam.pageSize"
        @pagination="doSearch"
      />
    </div>
    <!-- 选择盖章单位 -->
    <el-dialog
      v-if="dialogStampUnitVisible"
      ref="dialogStampUnitRef"
      v-dialogDrag
      :append-to-body="true"
      :modal-append-to-body="true"
      :modal="true"
      :close-on-click-modal="false"
      title="选择盖章单位"
      class="pms-dialog"
      :visible.sync="dialogStampUnitVisible"
    >
      <div class="signatoryBody">
        <StampUnit ref="stampUnitRef" :prj-id="prjId" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          class="pms-zr-button-primary"
          style="background-color: #eb4b4b; color: #fff;"
          size="small"
          @click="stampUnitSubmit"
        >确 定</el-button>
        <el-button
          class="pms-zr-button-primary"
          style="background-color: #eb4b4b; color: #fff;"
          size="small"
          @click="dialogStampUnitVisible = false"
        >取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择印章管理员弹框 -->
    <el-dialog
      v-if="dialogSignVisible"
      ref="dialogSignRef"
      v-dialogDrag
      :append-to-body="true"
      :modal-append-to-body="true"
      :modal="true"
      :close-on-click-modal="false"
      :title="signatoryTitle"
      class="pms-dialog"
      :visible.sync="dialogSignVisible"
    >
      <div class="signatoryBody">
        <SignatoryList
          ref="sealKeeperRef"
          flag-list="A"
          :row-org-code="rowOrgCode"
          :row-user-id="rowUserId"
          :seal-type="sealType"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          class="pms-zr-button-primary"
          style="background-color: #eb4b4b; color: #fff;"
          size="small"
          @click="submitSeal"
        >确 定</el-button>
        <el-button
          class="pms-zr-button-primary"
          style="background-color: #eb4b4b; color: #fff;"
          size="small"
          @click="dialogSignVisible = false"
        >取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择签署人弹框 -->
    <el-dialog
      v-if="dialogSealVisible"
      ref="dialogSealRef"
      v-dialogDrag
      :append-to-body="true"
      :modal-append-to-body="true"
      :modal="true"
      :close-on-click-modal="false"
      :title="signatoryTitle"
      class="pms-dialog"
      :visible.sync="dialogSealVisible"
    >
      <div class="signatoryBody">
        <SignatoryList
          ref="signatoryListRef"
          flag-list="B"
          :row-org-code="rowOrgCode"
          :row-user-id="rowUserId"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          class="pms-zr-button-primary"
          style="background-color: #eb4b4b; color: #fff;"
          size="small"
          @click="submitSignatory"
        >确 定</el-button>
        <el-button
          class="pms-zr-button-primary"
          style="background-color: #eb4b4b; color: #fff;"
          size="small"
          @click="dialogSealVisible = false"
        >取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
import store from '@/store'
import { Tooltip } from 'element-ui'
import MyTable from '@/components/basic/myTable'
import SysConst from '@/common/const'
import StampUnit from './stampUnit.vue'
import SignatoryList from './signatoryList.vue'
import { disableScroll, enableScroll, msgInfoEl } from '@/utils'
import {
    signatoryLabel,
    signatoryOperation
} from '.'
Vue.use(Tooltip)

import {
    querySealInfoApi,
    saveTemSealInfosApi,
    removeTemSealByIdsApi,
    addSignerApi,
    addSealApi
} from '@/api/attachmentInfo'

export default {
    name: 'ChooseSignatory',
    components: {
        MyTable,
        StampUnit,
        SignatoryList,
        Tooltip
    },
    filters: {
        signatorySeal(names) {
            if (!names || names === null) {
                return '请选择'
            } else {
                return names.split(',')[0]
            }
        }
    },
    props: {
        prjData: {
            type: Object,
            deep: true,
            default: () => ({})
        }
    },
    data() {
        return {
            signatoryData: [], // 签署人弹框数据
            signatoryLabel, // 签署人表头
            signatoryOperation, // 签署人操作按钮
            dialogStampUnitVisible: false, // 选择盖章单位弹框
            dialogSignVisible: false, // 选择印章管理员弹框
            dialogSealVisible: false, // 选择签署人弹框
            prjId: '', // 项目id
            rowOrgCode: '', // 数据单位编码
            rowUserId: '', // 印章管理员或者签署人id
            sealType: '', // 公司类型
            rowId: '', // 点击时主键id
            signatoryTitle: '',
            // 分页信息
            pageParam: {
                pageSize: SysConst.PAGESIZE, // 每页显示val条
                pageNum: SysConst.CURRENT_PAGE, // 当前页
                total: SysConst.TOTAL // 总数
            },
            chooseSealList: [],
            chooseSignList: []
        }
    },
    created() {
        this.doSearch()
    },
    methods: {
        doSearch(item) {
            console.log(this.prjData, 'this.prjData')
            if (!this.prjData.docType) {
                return msgInfoEl({
                    type: 'info',
                    message: '文件类型不能为空'
                })
            }
            const params = {
                pageNum: item?.page || SysConst.CURRENT_PAGE,
                pageSize: item?.limit || SysConst.PAGESIZE,
                isInit: item?.page ? 0 : 1, // 1,初始化，0，不初始化
                ...this.prjData
            }
            querySealInfoApi(params).then(res => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                } else {
                    console.log(res, '电子签章初始化')
                    this.signatoryData = res.data.records
                    this.pageParam.total = res.data?.total || 0
                    this.pageParam.pageSize = item?.limit || SysConst.PAGESIZE
                    this.pageParam.pageNum = item?.page || SysConst.CURRENT_PAGE
                }
            })
            console.log(params)
        },
        // 签署人按钮
        btnClick(fun, row) {
            this[fun](row)
        },
        // 新增
        add(row) {
            console.log(row, '新增--row')
            this.prjId = this.prjData.prjId
            this.dialogStampUnitVisible = true
            this.dialogEl('dialogStampUnitRef')
        },
        // 盖章单位新增确认
        stampUnitSubmit() {
            const temSealInfos = this.$refs.stampUnitRef.getSelectionStampUnit()
            if (!temSealInfos.length) {
                return msgInfoEl({
                    type: 'info',
                    message: '请选择至少一个盖章单位'
                })
            }
            if (!this.prjData.docType) {
                return msgInfoEl({
                    type: 'info',
                    message: '文件类型不能为空'
                })
            }
            const params = {
                ...this.prjData,
                temSealInfos
            }
            saveTemSealInfosApi(params).then(res => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                } else {
                    console.log(res, 'xinzneg')
                    this.dialogStampUnitVisible = false
                    this.doSearch({
                        page: SysConst.CURRENT_PAGE,
                        limit: SysConst.PAGESIZE
                    })
                }
            })
        },
        // 移除服务商
        delete(row) {
            console.log(row, '删除按钮--row')
            const params = {
                temIds: row.map(item => item.id)
            }
            const contentBody = window.top.document.body
            this.$confirm('确认移除所选数据, 是否继续?', '移除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                cancelButtonClass: 'pms-zr-button',
                confirmButtonClass: 'pms-zr-button-primary',
                closeOnClickModal: false
            }).then(() => {
                removeTemSealByIdsApi(params).then(res => {
                    if (+res.code !== 200) {
                        return Promise.reject(res)
                    } else {
                        console.log(res, '移除服务商')
                        this.doSearch({
                            page: this.pageParam.pageNum,
                            limit: this.pageParam.pageSize
                        })
                    }
                })
            }).catch(() => {
                enableScroll(contentBody)
                console.log('取消移除了')
            })
            // el-message-box__wrapper
            // 将弹框挂载在最外层
            this.$nextTick(() => {
                const msgBox = document.querySelector('.el-message-box__wrapper')
                contentBody.appendChild(msgBox)
                disableScroll(contentBody)
            })
        },
        // 列表表格点击
        rowClick(row, prop) {
            console.log(row, prop, 'row-prop')
        },
        // 上传 / 指派签署人弹框-点击列表印章管理员
        rowSales(row) {
            console.log(row, '印章管理员')
            if (row.signSealAdminList) {
                this.chooseSealList = row.signSealAdminList.split(',')
            }
            if (row.signSignersList) {
                this.chooseSignList = row.signSignersList.split(',')
            }
            this.signatoryTitle = '选择印章管理员'
            this.rowOrgCode = row.sealCompanyId
            this.rowUserId = row.signSealAdminList || ''
            this.sealType = row.sealType
            this.rowId = row.id
            this.dialogSignVisible = true
            this.dialogEl('dialogSignRef')
        },
        // 上传 / 指派签署人弹框-提交印章管理员
        submitSeal() {
            // const selectSeal = store.getters.getSelectPer
            const selectSeal = this.$refs.sealKeeperRef.getSelectPer
            console.log(selectSeal, '印章管理员选中数据')
            this.chooseSealList = selectSeal.map(item => item.userId)
            const flag = this.getSomeUser()
            if (flag) {
                return msgInfoEl({
                    type: 'warning',
                    message: '当前选择人员已存在该附件的签章工作，请选择其他人员'
                })
            } else {
                const params = {
                    id: this.rowId,
                    userId: selectSeal.map(item => item.userId).join()
                }
                addSealApi(params).then(res => {
                    if (+res.code !== 200) {
                        return Promise.reject(res)
                    } else {
                        this.dialogSignVisible = false
                        store.commit('settings/setToggleRowPer', {})
                        store.commit('settings/setSelectPer', [])
                        this.doSearch({
                            page: SysConst.CURRENT_PAGE,
                            limit: SysConst.PAGESIZE
                        })
                    }
                })
            }
        },
        // 上传 / 指派签署人弹框-点击列表签署人
        rowFileName(row) {
            console.log(row, '签署人')
            this.signatoryTitle = '选择签署人'
            if (row.signSealAdminList) {
                this.chooseSealList = row.signSealAdminList.split(',')
            }
            if (row.signSignersList) {
                this.chooseSignList = row.signSignersList.split(',')
            }
            this.rowOrgCode = row.sealCompanyId
            this.rowUserId = row.signSignersList || ''
            this.rowId = row.id
            this.dialogSealVisible = true
            this.dialogEl('dialogSealRef')
        },
        getSomeUser() {
            const status = []
            if (this.chooseSignList.length > 0 && this.chooseSealList.length > 0) {
                this.chooseSignList.forEach((item) => {
                    status.push(this.chooseSealList.some((subItem) => { return item === subItem }))
                })
            }
            return status.includes(true)
        },
        // 上传 / 指派签署人弹框-提交签署人
        submitSignatory() {
            // const selectSign = store.getters.getSelectPer
            const selectSign = this.$refs.signatoryListRef.getSelectPer
            this.chooseSignList = selectSign.map(item => item.userId)
            const flag = this.getSomeUser()
            if (flag) {
                return msgInfoEl({
                    type: 'warning',
                    message: '当前选择人员已存在该附件的签章工作，请选择其他人员'
                })
            } else {
                const params = {
                    id: this.rowId,
                    userId: selectSign.map(item => item.userId).join()
                }
                console.log(selectSign, '签署人选中数据')
                addSignerApi(params).then(res => {
                    if (+res.code !== 200) {
                        return Promise.reject(res)
                    } else {
                        this.dialogSealVisible = false
                        store.commit('settings/setToggleRowPer', {})
                        store.commit('settings/setSelectPer', [])
                        this.doSearch({
                            page: SysConst.CURRENT_PAGE,
                            limit: SysConst.PAGESIZE
                        })
                    }
                })
            }
        },
        // 将弹框挂载在最外层
        dialogEl(refName) {
            // 将弹框挂载在最外层
            const contentBody = window.top.document.body
            this.$nextTick(() => {
                const dialogModal = document.querySelector('.v-modal')
                contentBody.appendChild(this.$refs[refName].$el)
                contentBody.appendChild(dialogModal)
                disableScroll(contentBody)
            })
        },
        // 关闭弹框
        dialogClosed() {
            const contentBody = window.top.document.body
            enableScroll(contentBody)
        }
    }
}
</script>

<style lang="scss" scoped>
.el-button--text {
    color: #02A7F0;
}

.signatoryBody {
    max-height: 460px;
    overflow: auto;
}

.el-button--primary {
    color: #fff;
}
</style>
